<?php

namespace org\login;

use app\common\model\User;
use app\common\model\UserWx;
use fast\Random;
use think\Config;
use think\Db;
use think\Env;
use think\Queue;

class Wxapp
{
//微信小程序登陆第一步，需要现在后台微信配置 小程序配置里面配置好参数
    public function codeToInfo($code = '')
    {
        //根据code取openid和session_key
        $wx = new \org\Wx();
        $userWxModel = new UserWx();


        $config = [
            'appid'     => Env::get('WECHAT.MINI_PROGRAM_APPID', 'wx32eb6611f48aee1b'),
            'secret'    => Env::get('WECHAT.MINI_PROGRAM_SECRET', '95befcf50e382e87c977f0b3df8dc9b4'),
        ];

        $result = $wx->code_to_sessionkey($config['appid'], $config['secret'], $code);

        if (!$result['status']) {
            return $result;
        }
        if (isset($result['data']['unionid']) && $result['data']['unionid']) {
            $where['unionid'] = $result['data']['unionid'];
        } else {
            $where['openid'] = $result['data']['openid'];
        }
        $where['type'] = $userWxModel::TYPE_MINIPROGRAM;
        $info          = $userWxModel->where($where)->find();
        if ($info) {
            //更新session_key
            $userWxModel->save(['session_key' => $result['data']['session_key']], $where);
            $user_wx_id = $info['id'];
        } else {
            if (isset($result['data']['unionid']) && $result['data']['unionid']) {
                $data['unionid'] = $result['data']['unionid'];
            }
            $data['type']        = $userWxModel::TYPE_MINIPROGRAM;     //小程序类型
            $data['openid']      = $result['data']['openid'];
            $data['session_key'] = $result['data']['session_key'];
            $userWxModel->save($data);
            $user_wx_id = $userWxModel->id;
        }
        $result['data'] = $user_wx_id;
        return $result;
    }

    //微信小程序登陆第二步，根据微信端传过来的值解析用户数据,更新user_wx表
    public function updateWxInfo($id, $edata, $iv,$pid = 0)
    {
        $userWxModel = new UserWx();
        $info = $userWxModel->where(['id' => $id])->find();

        if (!$info) {
            $result['status'] = false;
            $result['msg'] = '未找到小程序用户！';
            return $result;
        }
        //解密数据信息
        $wx     = new \org\Wx();
        $result = $wx->decrypt($edata, $iv, $info['session_key']);
        if (!$result['status']) {
            return $result;
        }
        //加密信息里有openid或unionid，前台传过来的值查出来的数据里也有，需要判断是否一致，否则可能会有漏洞
        if ($info['openid'] != $result['data']['openId']) {
            $result['status'] = false;
            $result['msg'] = '微信用户信息不一致！';
            return $result;
        }

        if (isset($result['data']['openId']) && $result['data']['openId']) {
            $where['openId']    = ['eq', $result['data']['openId']];
            $where['user_id']    = ['neq', '0'];
            $wxUserInfo = $userWxModel->where($where)->find();
            if ($wxUserInfo) {
                $info['user_id'] = $wxUserInfo['user_id'];
                $data['user_id'] = $wxUserInfo['user_id'];
            }
        }
        //有会员的情况下不更新头像

        if (isset($info['avatar']) && !$info['avatar']) {
            //头像都按统一方法保存到本地或者远程图片服务器
        }

        $data['id']       = $info['id'];
        $data['type']     = $userWxModel::TYPE_MINIPROGRAM;
        $data['avatar']   = $result['data']['avatarUrl'];
        $data['nickname'] = $result['data']['nickName'];
        $data['gender']   = $result['data']['gender'];
        $data['language'] = $result['data']['language'];
        $data['city']     = $result['data']['city'];
        $data['province'] = $result['data']['province'];
        $data['country']  = $result['data']['country'];

        //更新userWx
        $userWxModel->save($data, ['id' => $data['id']]);

        $ret = $this->direct($data,$pid);


        if ($ret) {

            $result['status'] = true;
            $result['msg'] = '登录成功！';
        } else {
            $result['status'] = false;
            $result['msg'] = '登录失败';
        }

        return $result;
    }

    public function direct($data, $pid){
        $auth = \app\common\library\Auth::instance();

        //设置会话有效时间 永久
        $keeptime = 0;
        $auth->keeptime($keeptime);

        if (isset($data['user_id'])) {
            $user = User::get($data['user_id']);
            if (!$user) {
                return false;
            }
            //$third->save($values);
            return $auth->direct($user->id);
        } else {
            // 先随机一个用户名,随后再变更为u+数字id
            $username = Random::alnum(20);
            $password = Random::alnum(6);
            $domain = request()->host();

            $userWxModel = new UserWx();
            Db::startTrans();
            try {
                //会员扩展信息
                $extend = [];
                // 默认注册一个会员
                $result = $auth->register($username, $password, $username . '@' . $domain, '', $extend);
                if (!$result) {
                    return false;
                }
                $user = $auth->getUser();
                $fields = ['username' => 'u' . $user->id, 'email' => 'u' . $user->id . '@' . $domain];
                if (isset($data['nickname'])) {
                    $fields['nickname'] = $data['nickname'];
                }
                if (isset($data['avatar'])) {
                    $fields['avatar'] = $data['avatar'];
                }

                //TODO 可后台配置 新用户送会员时长
                $fields['group_id'] = 1;
                $reg_free_member_days = Config::get('site.reg_free_member_days');
                if ($reg_free_member_days > 0){
                    $day = '+' . $reg_free_member_days . ' day';
                    $fields['expiretime'] = strtotime($day);
                }

                //邀请人 被邀请人 增加幸运等级
                if ($pid){
                    $fields['level'] = $user->level + 1;
                    //邀请人通过延时队列增加
                    $job = 'Invited';
                    $queue = 'invited';
                    $param = [
                        'pid'   => $pid
                    ];
                    //加入延时队列 5秒后
                    $isPushed = Queue::later(5,$job,$param,$queue);
                }

                // 更新会员资料
                $user = User::get($user->id);
                $user->save($fields);

                // 保存第三方信息
                $values['user_id'] = $user->id;
                //更新userWx
                $userWxModel->save($values, ['id' => $data['id']]);

                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $auth->logout();
                return false;
            }

            // 写入登录Cookies和Token
            return $auth->direct($user->id);
        }
    }
}
